﻿using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SDPChecker
{
    public class AssemblyInfo
    {
        public AssemblyInfo(string name)
        {
            Name = name;
            Value = 0M;
            Dependencies = new List<AssemblyInfo>();
        }

        public AssemblyInfo(string name, decimal value) : this(name)
        {
            Value = value;
        }

        public AssemblyInfo(string name, IEnumerable<AssemblyInfo> assemblies)
            : this(name)
        {
            Dependencies = assemblies;
        }

        private AssemblyInfo(string name, decimal value, IEnumerable<AssemblyInfo> dependencies) : this(name, value)
        {
            Dependencies = dependencies;
        }

        public string Name { get; private set; }
        public decimal Value { get; set; }

        public IEnumerable<AssemblyInfo> Dependencies { get; private set; }

        public bool IsBadBoy
        {
            get { return Dependencies.Any(dependency => dependency.Value > Value); }
        }

        public AssemblyInfo CreateCopyWithInstabilityValues(IDictionary<string, AssemblyInfo> instableAssemblies)
        {
            return new AssemblyInfo(Name, 
                instableAssemblies.ContainsKey(Name) ? instableAssemblies[Name].Value : 0,
                DepenciesCopy(instableAssemblies).ToList());            
        }

        private IEnumerable<AssemblyInfo> DepenciesCopy(IDictionary<string, AssemblyInfo> instableAssemblies)
        {
            return (from dependency in Dependencies where instableAssemblies.ContainsKey(dependency.Name) select new AssemblyInfo(dependency.Name, instableAssemblies[dependency.Name].Value));
        }

        public string ToOutputString()
        {
            var builder = new StringBuilder(string.Format("Assembly {0} with I:{1} depends on:\r\n", Name, Value));
            foreach(var dep in Dependencies.Where(dependency => dependency.Value > Value))
            {
                builder.Append(string.Format("Assembly {0} with I:{1}\r\n", dep.Name, dep.Value));
            }
            return builder.Append("\r\n").ToString();
        }
    }
}
